const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.get('/get-comment', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  const { news_id, comment_level, sqltype, page_index, page_size } = req.query
  if (
    !Bee.StringUtils.isNotBlank(sqltype) ||
    !Bee.StringUtils.isNotBlank(news_id) ||
    !Bee.StringUtils.isNumber(comment_level * 1) ||
    !Bee.StringUtils.isNumber(page_index * 1) ||
    !Bee.StringUtils.isNumber(page_size * 1)
  )
    return handleError(10003, '参数错误')

  // sqltype 个位数: 0 = 降序  1 = 升序

  const sql = `SELECT com.id, com.user_id, com.user_name, com.news_id, com.comment_level, com.praise_num, com.top_status, com.created_time, com.content, GROUP_CONCAT(CONCAT('{"id":',rep.id,',"user_name":"',rep.user_name,'","reply_comment_user_id":',rep.user_id,',"reply_comment_id":',com.id,',"content":"',rep.content,'","created_time":"',rep.created_time,'","praise_num":',rep.praise_num,',"news_id":',rep.news_id,',"comment_level":',rep.comment_level,'}')) AS children_comment_list FROM comment com LEFT  JOIN comment rep ON com.id=rep.parent_comment_id WHERE com.parent_comment_id=0 AND com.news_id IN (?) GROUP BY com.id  ORDER BY top_status ${
    Bee.StringUtils.getStrLast(sqltype, 1) === '0' ? 'DESC' : 'ASC'
  } ,created_time ${
    Bee.StringUtils.getStrLast(sqltype, 1) === '0' ? 'DESC' : 'ASC'
  } LIMIT ?,?`
  const totalSql = `SELECT count(*) FROM comment WHERE news_id IN (?) AND comment_level = 1 ORDER BY top_status ${
    Bee.StringUtils.getStrLast(sqltype, 1) === '0' ? 'DESC' : 'ASC'
  } ,created_time ${
    Bee.StringUtils.getStrLast(sqltype, 1) === '0' ? 'DESC' : 'ASC'
  } LIMIT ?,?`

  const sqlParams = [
    news_id.split(','), // 以 ，转数组
    // comment_level,
    (parseInt(page_index) - 1) * parseInt(page_size),
    parseInt(page_size),
  ]

  // 获取数据总条数
  const [getTotalError, getTotalSuccess] = await to(
    db.query(totalSql, sqlParams)
  )
  if (getTotalError || !getTotalSuccess) return handleError(-1, getTotalError)
  const total = getTotalSuccess[0]['count(*)'] // 数据总条数

  const [getCommentError, getCommentSuccess] = await to(
    db.query(sql, sqlParams)
  )
  if (getCommentError || !getCommentSuccess)
    return handleError(-1, getCommentError)

  getCommentSuccess.forEach((item) => {
    console.log(JSON.parse('[' + item.children_comment_list + ']'))
    item.children_comment_list = item.children_comment_list
      ? JSON.parse('[' + item.children_comment_list + ']')
      : null
  })
  return resp.json({
    code: 0,
    msg: status_code[0],
    data: {
      list: getCommentSuccess,
      total: total,
    },
  })
})

module.exports = router
